<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <el-radio-group v-model="tableType" :disabled="baseData.loading" @change="getAxiosData(true)">
            <el-radio-button label="按天查看" :value="0"></el-radio-button>
            <el-radio-button label="按合作方查看" :value="1"></el-radio-button>
          </el-radio-group>
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <!--          <bubble-select-local -->
          <!--            v-model="filterData.orderPlatform" -->
          <!--            labelKey="label" -->
          <!--            valueKey="value" -->
          <!--            :filterable="false" -->
          <!--            style="width: 230px" -->
          <!--            :list="[ -->
          <!--              { label: '全部', value: '' }, -->
          <!--              { label: '快手', value: 'mp-kuaishou' }, -->
          <!--              { label: '抖音', value: 'mp-toutiao' }, -->
          <!--              { label: '抖音', value: 'mp-weixin' }, -->
          <!--            ]" -->
          <!--            placeholder="请选择消费平台" -->
          <!--            @change="getAxiosData(true)" -->
          <!--          ></bubble-select-local> -->
          <!--          <bubble-select-local -->
          <!--            v-model="filterData.payChannel" -->
          <!--            labelKey="label" -->
          <!--            valueKey="value" -->
          <!--            :filterable="false" -->
          <!--            style="width: 230px" -->
          <!--            :list="[ -->
          <!--              { label: '全部', value: '' }, -->
          <!--              { label: '微信', value: 'WECHAT' }, -->
          <!--              { label: '支付宝', value: 'ALIPAY' }, -->
          <!--            ]" -->
          <!--            placeholder="请选择支付渠道" -->
          <!--            @change="getAxiosData(true)" -->
          <!--          ></bubble-select-local> -->
          <!--          <base-input-search -->
          <!--            v-model="filterData.dramaTitle" -->
          <!--            clearable -->
          <!--            placeholder="请输入剧名" -->
          <!--            style="width: 230px" -->
          <!--            maxlength="30" -->
          <!--            :prefixIcon="IconSearch" -->
          <!--            @submit="getAxiosData(true)" -->
          <!--          ></base-input-search> -->
          <!--          <base-input-search -->
          <!--            v-model="filterData.referralLinkId" -->
          <!--            clearable -->
          <!--            placeholder="请输入充值链接ID" -->
          <!--            style="width: 230px" -->
          <!--            maxlength="30" -->
          <!--            :prefixIcon="IconSearch" -->
          <!--            @submit="getAxiosData(true)" -->
          <!--          ></base-input-search> -->
          <!--          <base-input-search -->
          <!--            v-model="filterData.promotionId" -->
          <!--            clearable -->
          <!--            placeholder="请输入广告ID" -->
          <!--            style="width: 230px" -->
          <!--            maxlength="30" -->
          <!--            :prefixIcon="IconSearch" -->
          <!--            @submit="getAxiosData(true)" -->
          <!--          ></base-input-search> -->
        </div>
      </div>
    </template>
    <div class="page-content">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value" :class="{ 'operable': i.type === 'primary' }">{{ i.format(censusData) }}</div>
        </div>
      </div>
      <el-table
        v-show="tableType === 0"
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        showOverflowTooltip
        stripe
        style="width: 100%"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column label="日期" align="center" prop="dayTime" minWidth="180"></el-table-column>
        <el-table-column label="总金额" align="center" prop="totalAmount" minWidth="180"></el-table-column>
      </el-table>
      <el-table
        v-show="tableType === 1"
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        :spanMethod="spanMethodsHandler"
        showOverflowTooltip
        stripe
        style="width: 100%"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column label="合作方" align="center" prop="partnerUserName" minWidth="180"></el-table-column>
        <el-table-column label="短剧" align="center" prop="dramaTitle" minWidth="180"></el-table-column>
        <el-table-column label="总金额" align="center" prop="totalAmount" minWidth="180"></el-table-column>
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  // import IconSearch from '~icons/ep/search';
  import {
    type AppUserSavingsListRequest,
    type OrderTotalAmountDataItem,
    getOrderPriceAllAxios,
    getOrderTotalAmountData,
    getPartnerUserData,
  } from '@/api/app-user-management.ts';
  import { formatNumberWithMoney } from '@/utils/numb.ts';
  import type { TableColumnCtx } from 'element-plus';
  const { proxy } = getCurrentInstance() as any;

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const tableType = ref<0 | 1>(0);
  const dataRange = ref<[string, string] | undefined>();
  const filterData: Ref<AppUserSavingsListRequest> = ref<AppUserSavingsListRequest>({
    orderPlatform: undefined,
    outTradeNo: '',
    payChannel: '',
    status: '',
    dramaTitle: '',
    startDate: '',
    endDate: '',
    referralLinkId: '',
    promotionId: '',
    current: 1,
    size: 40,
    userId: '',
    devicePlatform: '',
  });

  const tableData: Ref<OrderTotalAmountDataItem[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    dataRange.value = [proxy.$dayjs().subtract('6', 'M').format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
  });

  /** 统计数据 */
  const censusData = ref<Record<'priceAll', number>>({
    priceAll: 0,
  });

  let spanArr: number[] = [];
  const getSpanArr = (data: OrderTotalAmountDataItem[]) => {
    spanArr = [];
    let pos = 0;
    for (let i = 0; i < data.length; i++) {
      if (i === 0) {
        spanArr.push(1);
        pos = 0;
      } else {
        if (data[i]?.partnerUserName === data[i - 1]?.partnerUserName) {
          spanArr[pos]! += 1;
          spanArr.push(0);
        } else {
          spanArr.push(1);
          pos = i;
        }
      }
    }
  };

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = `${dataRange.value[0]} 00:00:00`;
      filterData.value.endDate = `${dataRange.value[1]} 23:59:59`;
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = tableType.value === 0 ? await getOrderTotalAmountData(filterData.value) : await getPartnerUserData(filterData.value);
      if (tableType.value === 1) {
        getSpanArr(res.data.records);
        if (res.data.records && res.data.records.length) {
          censusData.value.priceAll = res.data.records[0]?.partnerUserAllTotalAmount || 0;
        }
      } else {
        const { data } = await getOrderPriceAllAxios(filterData.value);
        censusData.value.priceAll = data?.totalAmount || 0;
      }
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  interface StatisticsItem {
    name: string;
    flag: 'priceAll';
    type?: string;
    format: (val: Record<'priceAll', number>) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '总金额',
      flag: 'priceAll',
      format(val) {
        return formatNumberWithMoney(val?.priceAll || 0) ?? 0;
      },
    },
  ]);

  interface SpanMethodProps {
    row: any;
    column: TableColumnCtx<any>;
    rowIndex: number;
    columnIndex: number;
  }
  const spanMethodsHandler = ({ columnIndex, rowIndex }: SpanMethodProps) => {
    if (columnIndex === 0) {
      const _row = spanArr[rowIndex]!;
      const _col = _row! > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col,
      };
    }
    return undefined;
  };
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .page-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .order-status {
    box-sizing: border-box;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 20px;
    padding: 0 7px;
    font-size: 12px;
    line-height: 12px;
    color: #ffffff;
    border-radius: 5px;

    /* 异常状态 */
    &.abnormal {
      color: var(--el-color-danger);
      background-color: var(--el-color-danger-light-9);
      border: 1px solid var(--el-color-danger-light-5);
    }

    /* 待支付状态 */
    &.pending-payment {
      color: var(--el-color-warning);
      background-color: var(--el-color-warning-light-9);
      border: 1px solid var(--el-color-warning-light-8);
    }

    /* 已支付状态 */
    &.paid {
      color: var(--el-color-success);
      background-color: var(--el-color-success-light-9);
      border: 1px solid var(--el-color-success-light-8);
    }

    /* 支付失败状态 */
    &.payment-failed {
      color: var(--el-color-danger);
      background-color: var(--el-color-danger-light-9);
      border: 1px solid var(--el-color-danger-light-8);
    }

    /* 已退款状态 */
    &.refunded {
      color: var(--el-color-violet);
      background-color: var(--el-color-violet-light-9);
      border: 1px solid var(--el-color-violet-light-8);
    }

    /* 已关闭状态 */
    &.closed {
      color: var(--el-color-info);
      background-color: var(--el-color-info-light-9);
      border: 1px solid var(--el-color-info-light-8);
    }

    /* 未知状态 */
    &.unknown {
      color: var(--el-color-cyan);
      background-color: var(--el-color-cyan-light-9);
      border: 1px solid var(--el-color-cyan-light-8);
    }
  }
</style>
